#include "relay_output.h"
#include "platformAPI.h"


#define DEBUG_TASK_RELAY 1

#ifdef DEBUG_TASK_KEY
#include "stdio.h"
#endif

#define RELAY_IO 12

static uint8_t relay_state;

void updateRelayStateToRemote(void)
{
    cJSON *cjson_param = NULL;
    int8 *param = NULL;
    cjson_param = cJSON_CreateObject();
    if(cjson_param)
    {
	if(relay_state == RELAY_ON)
	{
	    cJSON_AddItemToObject(cjson_param,"switch",cJSON_CreateString("on"));
	}
	else
	{
	    cJSON_AddItemToObject(cjson_param,"switch",cJSON_CreateString("off"));
	}
    }
    
    param = cJSON_Print(cjson_param);
    printf("param is \n%s\n",param);
    iotgoWriteUpdateToServer(param);
    free(param);
    cJSON_Delete(cjson_param);
}

void turnOnRelay(void)
{
    GPIO_OUTPUT_SET(GPIO_ID_PIN(RELAY_IO),1);
    relay_state = RELAY_ON;
    printf("relay on\n");
}

void turnOffRelay(void)
{
    GPIO_OUTPUT_SET(GPIO_ID_PIN(RELAY_IO),0);
    relay_state = RELAY_OFF;
    printf("relay off\n");
}

/* relay update message parse*/
void relayUpdateByRemote(uint8_t *sequence, int8_t *params)
{
    cJSON *cjson_params = NULL;
    cJSON *cjson_switch = NULL;

    cjson_params = cJSON_Parse(params);
    if(cjson_params)
    {
	cjson_switch = cJSON_GetObjectItem(cjson_params,"switch");
	if(cjson_switch)
	{
	    printf("switch update to state %s\n",cjson_switch->valuestring);
	    if(strcmp(cjson_switch->valuestring,"on") == 0)
	    {
		turnOnRelay();
	    }
	    else if(strcmp(cjson_switch->valuestring,"off") == 0)
	    {
		turnOffRelay();
	    }
	}
	iotgoWriteErrorNumToServer(0,sequence);
        cJSON_Delete(cjson_params);     
    }
}

void relayUpdateByLocal(void)
{
    if(relay_state == RELAY_ON)
    {
	turnOffRelay();
    }
    else
    {
	turnOnRelay();
    }
    updateRelayStateToRemote();
}

int initRelay(void)
{
    PIN_FUNC_SELECT(GPIO_PIN_REG(12),FUNC_GPIO12); /* this is for relay*/
    PIN_PULLUP_EN(GPIO_PIN_REG(12));

    turnOffRelay();
    return 0;
}
